package com.hbm.dao.impl;

import java.util.List;
import java.util.Scanner;

import com.hbm.dao.CustomerDao;
import com.hbm.entity.Customer;
import com.hbm.util.BeanFactory;
import com.hbm.util.HibernateTemplate;

public class CustomerDaoImpl implements CustomerDao {
	static Scanner scanner = new Scanner(System.in);

	@Override
	public void insertCustomer(Customer customer) {
		Customer s = selectCustomerById(customer.getId());
		if (s == null) {
			HibernateTemplate.execute(ses -> {
				ses.save(customer);
				System.out.println("增加成功！");
				return null;
			});
		} else {
			System.out.println("该客户已存在!");
		}

	}

	@Override
	public void delectCustomer() {
		System.out.println("请您输入编号：");
		long nextInt = scanner.nextInt();
		BeanFactory.getBean("customerDao");
		Customer s = selectCustomerById(nextInt);
		if (s != null) {
			HibernateTemplate.execute(ses -> {
				ses.delete(s);
				System.out.println("删除成功！");
				return null;
			});
		} else {
			System.out.println("该客户不存在!");
		}

	}

	@Override
	public void updateCustomer(Customer customer) {
		Customer s = selectCustomerById(customer.getId());
		if (s == null) {
			System.out.println("该客户不存在,请勿修改!");
		} else {
			HibernateTemplate.execute(ses -> {
				ses.update(customer);
				System.out.println("修改成功！");
				return null;
			});
		}

	}

	@Override
	public Customer selectCustomerById(Long id) {
		return (Customer) HibernateTemplate.execute(ses -> ses.get(Customer.class, id));

	}

	@Override
	public Customer selectCustomerByName(String name) {
		return (Customer) HibernateTemplate.execute(
				ses -> ses.createQuery("from Customer where name=:name").setParameter("name", name).uniqueResult());
	}

	@Override
	public Customer selectCustomerByAddress(String address) {
		return (Customer) HibernateTemplate.execute(ses -> ses.createQuery("from Customer where address=:address ")
				.setParameter("address", address).uniqueResult());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Customer> selectAllCustomers() {
		return (List<Customer>) HibernateTemplate.execute(ses -> ses.createQuery("from Customer").list());
	}

}
